﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommunityServer.WebServices.MediaGalleries;
using System.Diagnostics;
using System.Threading;
using System.Web;

namespace nb.development.csmediamanager
{
    public partial class ItemProperties : Form
    {
        public ItemProperties(MediaGalleryPost post, Guid siteid)
        {
            InitializeComponent();
            this.siteid = siteid;
            this.post = post;
            MenuItem i = new MenuItem("&Copy");
            i.DefaultItem = true;
            i.Click += new EventHandler(copy_Click);
            PostURL.ContextMenu = new ContextMenu(new MenuItem[] { i });
            i = new MenuItem("&Copy");
            i.DefaultItem = true;
            i.Click += new EventHandler(copy2_Click);
            MediaURL.ContextMenu = new ContextMenu(new MenuItem[] { i });
            init();
        }

        private void init()
        {
            btnChange.Enabled = Sites.Instance.EnableEditing;
            description.Text = HttpUtility.HtmlDecode(post.Body);
            created.Text = post.Date.Value.ToLongDateString() + " " + post.Date.Value.ToLongTimeString();
            title.Text = HttpUtility.HtmlDecode(post.Title);
            PostURL.Text = post.Url;
            MediaURL.Text = post.Attachment.Endpoint;
            MediaFileName.Text = HttpUtility.HtmlDecode(post.Attachment.Endpoint.Remove(0, post.Attachment.Endpoint.LastIndexOf('/') + 1));
            published.Checked = post.IsPublished.Value;
            List<string> s = new List<string>();
            foreach (string st in post.Keywords)
                s.Add(HttpUtility.HtmlDecode(st));
            tags.Text = HttpUtility.HtmlDecode(string.Join(", ", s.ToArray()));
            this.Text = string.Format(this.Text, HttpUtility.HtmlDecode(post.Title));
            btnApply.Enabled = false;
        }

        public event EventHandler Saved;

        private Guid siteid;
        private MediaGalleryPost post;

        private void panel_Paint(object sender, PaintEventArgs e)
        {
            Panel p = sender as Panel;
            e.Graphics.DrawLine(new Pen(Color.FromArgb(160, 160, 160)), 1, 1, p.Width, 1);
        }

        private void panel5_Paint(object sender, PaintEventArgs e)
        {
            string s = post.Attachment.Endpoint.Substring(post.Attachment.Endpoint.LastIndexOf('.'));
            if (s.Length > 5) {
                if (s.ToCharArray()[s.Length - 4] == '_') s = '.' + s.Substring(s.Length - 3);
                else if (s.ToCharArray()[s.Length - 5] == '_') s = '.' + s.Substring(s.Length - 4);
            }
            e.Graphics.DrawIconUnstretched(IconHelper.ExtractIconForExtension(s, true), new Rectangle(0, 0, 32, 32));
        }

        private void MediaURL_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                ProcessStartInfo sInfo = new ProcessStartInfo(((Label)sender).Text);
                try { Process.Start(sInfo); }
                catch { }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            if (check())
            {
                this.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                List<MediaGalleryPost> posts = new List<MediaGalleryPost>();
                post.Title = HttpUtility.HtmlEncode(title.Text);
                post.Body = HttpUtility.HtmlEncode(description.Text);
                post.IsPublished = published.Checked;
                post.Keywords.Clear();
                foreach (string s in tags.Text.Split(new char[] { ','}))
                    post.Keywords.Add(HttpUtility.HtmlEncode(s.Trim()));
                posts.Add(this.post);
                Updater u = new Updater(posts, siteid);
                u.UpdateCompleded += new UploadCompleted(u_UpdateCompleded);
                Thread t = new Thread(new ThreadStart(u.Update));
                t.Start();
            } else this.Close();
        }

        void u_UpdateCompleded()
        {
            if (this.InvokeRequired)
            {
                UploadCompleted done = new UploadCompleted(u_UpdateCompleded);
                try { this.Invoke(done); }
                catch { }
            }
            else { if (Saved != null) Saved(this, new EventArgs());  this.Close(); }
        }

        private void title_KeyUp(object sender, KeyEventArgs e)
        {
            btnApply.Enabled = check();
        }

        private void published_CheckedChanged(object sender, EventArgs e)
        {
            btnApply.Enabled = check();
        }

        private void description_KeyUp(object sender, KeyEventArgs e)
        {
            btnApply.Enabled = check();
        }

        private void tags_KeyUp(object sender, KeyEventArgs e)
        {
            btnApply.Enabled = check();
        }

        private bool check()
        {
            if (title.Text != post.Title) return true;
            if (description.Text != post.Body) return true;
            if (published.Checked != post.IsPublished.Value) return true;
            List<string> strings = new List<string>();
            foreach (string s in post.Keywords)
                strings.Add(s);
            if (tags.Text != string.Join(", ", strings.ToArray())) return true;
            return false;
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            List<MediaGalleryPost> posts = new List<MediaGalleryPost>();
            post.Title = HttpUtility.HtmlEncode(title.Text);
            post.Body = HttpUtility.HtmlEncode(description.Text);
            post.IsPublished = published.Checked;
            post.Keywords.Clear();
            foreach (string s in tags.Text.Split(new char[] { ',' }))
                post.Keywords.Add(HttpUtility.HtmlEncode(s.Trim()));
            posts.Add(this.post);
            Updater u2 = new Updater(posts, siteid);
            u2.UpdateCompleded += new UploadCompleted(u2_UpdateCompleded);
            Thread t = new Thread(new ThreadStart(u2.Update));
            t.Start();
        }

        void u2_UpdateCompleded()
        {
            if (this.InvokeRequired)
            {
                UploadCompleted done = new UploadCompleted(u2_UpdateCompleded);
                try { this.Invoke(done); }
                catch { }
            }
            else { if (Saved != null) Saved(this, new EventArgs()); this.Enabled = true; this.Cursor = Cursors.Default; btnApply.Enabled = false; }
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            MediaGallery g = Sites.Instance[this.siteid].Service.GetMediaGallery(this.post.MediaGalleryId.Value);
            FileAttachment fa = new FileAttachment(g, this.siteid, this.post);
            if (fa.ShowDialog(this) == DialogResult.OK)
            {
                Thread t = new Thread(new ThreadStart(reinit));
                t.Start();
            }
        }

        private void reinit()
        {
            MediaGalleryPost p2 = Sites.Instance[siteid].Service.GetMediaGalleryPost(this.post.Id);
            ReInitCompleted done = new ReInitCompleted(ReinitCompleted);
            try { this.Invoke(done, p2); }
            catch { }
        }

        private void ReinitCompleted(MediaGalleryPost post)
        {
            this.post = post;
            this.Enabled = true;
            this.Cursor = Cursors.Default;
            init();
        }

        private void copy2_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(post.Attachment.Endpoint);
        }

        private void copy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(post.Url);
        }
    }

    public delegate void ReInitCompleted(MediaGalleryPost post);
}
